package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 15分钟未支付订单任务处理（超时未支付订单）
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void timeoutOrderTask(){
        log.info("超时未支付订单检测定时任务执行...");
        //1、查询下单时间小于（当前时间-15）并且状态为待支付的订单
        //select * from orders where status = 1 and order_time < (当前时间 - 15分钟)
        final LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = ordersMapper.queryByStatusAndOrderTime(Orders.PENDING_PAYMENT,dateTime);

        //2、循环或者批量修改订单状态（状态、取消时间、取消原因）
        /*for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时，自动取消");
            ordersMapper.update(orders);
        }*/

        //update orders set status = 1,cancel_time = #{},cacel_reason = #{} where id in ();
        if(ObjectUtils.isNotEmpty(ordersList)) {
            final List<Long> ids = ordersList.stream().map(order -> order.getId()).collect(Collectors.toList());
            final Orders build = Orders.builder().status(Orders.CANCELLED).cancelTime(LocalDateTime.now()).cancelReason("订单超时，自动取消").build();
            this.ordersMapper.batchUpdate(ids, build);
        }
    }

    /**
     * 前一日未完成订单检测定时任务执行（超时未完成订单）
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void deliveryOrderTask(){

        //1、查询下单时间小于（当前时间-60）并且状态为待支付的订单
        //select * from orders where status = 4 and order_time < (当前时间 - 60分钟)
        final LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = ordersMapper.queryByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,dateTime);

        //2、循环或者批量修改订单状态（状态、取消时间、取消原因）
        //update orders set status = 5 where id in ();
        if(ObjectUtils.isNotEmpty(ordersList)) {
            final List<Long> ids = ordersList.stream().map(order -> order.getId()).collect(Collectors.toList());
            final Orders build = Orders.builder().status(Orders.COMPLETED).build();
            this.ordersMapper.batchUpdate(ids, build);
        }
    }


}